package com.woke.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.woke.AddfriendActivity;
import com.example.woke.LoadActivity;
import com.example.woke1.FriendsActivity;
import com.google.gson.Gson;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.ui.dialog.DialogMaker;
import com.netease.nim.uikit.support.permission.MPermission;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.silent.handle.CharacterParser;
import com.silent.handle.PinyinComparator1;
import com.silent.handle.SideBar;
import com.silent.handle.SideBar.OnTouchingLetterChangedListener;
import com.woke.data.Datas_freinds;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.model.YxListEvent;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.prefs.Preferences;

import cn.xl.xxl.imagecache.ImageLoader;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class NearbyFragment extends Fragment implements OnClickListener, OnItemClickListener,EasyPermissions.PermissionCallbacks {

    private View layout;
    private LayoutInflater minflater;
    private ListView mListView;
    private MyApp application;
    private ArrayList<Datas_freinds> datalist = new ArrayList<Datas_freinds>();
    private Myadapter adapter;
    private ImageLoader imageLoader;
    private AlertDialog alertDialog;
    private boolean showdian;
    private ImageView target;
    private ImageView mDian;
    private Datas_load loaded;
    private EditText mEcarno;
    /**
     * ����ת����ƴ������
     */
    private CharacterParser characterParser;
    /**
     * ���ƴ��������ListView����������
     */
    private PinyinComparator1 pinyinComparator;
    private SideBar sideBar;
    private boolean isFirst = true;
    private AbortableFuture<LoginInfo> loginRequest;

    private static final int BASIC_PERMISSION_REQUEST_CODE = 100;
    private static final int READ_AND_WRITE_STORE_MY = 9;

    String accid;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            methodRequiresTwoPermission ();
//        }
        EventBus.getDefault().register(this);
        if (layout == null) {
            minflater = inflater;
            imageLoader = new ImageLoader(getActivity());
            layout = minflater.inflate(R.layout.frment_nearby, null);
            intview();//һ�ڲ���
        } else {
            ViewGroup parent = (ViewGroup) layout.getParent();
            if (parent != null) {
                parent.removeView(layout);
            }
        }
        return layout;
    }

    @Override
    public void onDestroy() {
        imageLoader.clearCache();
        imageLoader.clearMemoryCache();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void intview() {

        application = (MyApp) getActivity().getApplication();
        target = (ImageView) layout.findViewById(R.id.fmfriend_up_right);
        mDian = (ImageView) layout.findViewById(R.id.fmfriend_up_dian);
        layout.findViewById(R.id.fmnearby_relative_friend).setOnClickListener(this);

        mListView = (ListView) layout.findViewById(R.id.fmnearby_listview);
        mListView.setOnItemClickListener(this);
        adapter = new Myadapter();
        mListView.setAdapter(adapter);

        layout.findViewById(R.id.fmnearby_imge_add).setOnClickListener(this);

        // ʵ����תƴ����
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator1();
        sideBar = (SideBar) layout.findViewById(R.id.sidrbar22);
        // �����Ҳഥ������
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // ����ĸ�״γ��ֵ�λ��
                Log.e("" + s, "" + s.charAt(0));
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    if (position < adapter.getCount()) {
                        mListView.setSelection(position);
                    }
                }

            }
        });

        mEcarno = (EditText) layout.findViewById(R.id.fmnearby_edit_ser);
        mEcarno.addTextChangedListener(watcher);

    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String trim = "" + mEcarno.getText().toString().trim();
            if (trim.equals("")) {
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
            } else {
                int length = trim.length();
//	    		Log.e("length", ""+length);
                for (int i = 0; i < datalist.size(); i++) {
                    if (datalist.get(i).name.length() >= length) {
                        if (datalist.get(i).name.substring(0, length).endsWith(trim)) {
                            mListView.setSelection(i);
                            return;
                        }
                    }
                }
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        Log.e("onResume", "onResume");
        loaded = application.getDatas_load();
        if (null == loaded) {
            if (isFirst) {
                isFirst = false;
            } else {
                aralogid("还未登录", "前往登录", 1);
            }
        } else {
//            getfriendlist();
            getYunxunList();
            getnewfriend();
        }
    }

    private void getnewfriend() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getActivity());
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "user");
        params.put("a", "newFridenlist");
        params.put("userid", loaded.getId());
        Log.e("params", params.toString());
        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("新好友列表", "请求" + response);
                try {
                    String flag = response.getString("flag");
                    if (flag.equals("success")) {
                        JSONObject object = response.getJSONObject("data");
                        JSONArray jsonArray = object.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object2 = jsonArray.getJSONObject(i);
                            String id = object2.getString("id");
                            String touser = object2.getString("touser");
                            String fromuser = object2.getString("fromuser");
                            String head = object2.getString("head");
                            String status = object2.getString("status");
                            String name = object2.getString("name");
                            if (status.equals("1")) {
                                showdian = true;
                                mDian.setVisibility(View.VISIBLE);
                            } else {
                                if (showdian == true) {

                                } else {
                                    mDian.setVisibility(View.GONE);
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    private void aralogid(String info, String kll, final int ppp) {
        alertDialog = new AlertDialog.Builder(getActivity()).
                setTitle(info).
                setMessage(kll).
//	                setIcon(R.drawable.ic_launcher).
        setPositiveButton("确定", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), LoadActivity.class);
        startActivity(intent);
        alertDialog.dismiss();
    }
}).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                alertDialog.dismiss();
                                // TODO Auto-generated method stub
                            }
                        }).create();
        alertDialog.show();
    }

    private void getfriendlist() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(getActivity());
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "user");
        params.put("a", "myFridenlist");
        params.put("userid", loaded.getId());
        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                datalist.clear();
                Log.e("上传", "手机号" + response);
                try {
                    String flag = response.getString("flag");
                    if (flag.equals("success")) {
                        datalist.clear();
                        JSONObject object = response.getJSONObject("data");
                        String string = object.getString("data");
                        ArrayList<Datas_freinds> changelist = (ArrayList<Datas_freinds>) com.alibaba.fastjson.JSONArray
                                .parseArray(string, Datas_freinds.class);
                        datalist.addAll(changelist);
                        for (int i = 0; i < changelist.size(); i++) {
                            // ����ת����ƴ��
                            String sortString = "";
                            String name = changelist.get(i).getName();
                            String pinyin = "#";
                            Log.e("name", "ss" + name);
                            if (null != name) {
                                pinyin = characterParser.getSelling(name);
                            }
                            if (null != pinyin && !pinyin.equals("")) {
                                sortString = pinyin.substring(0, 1).toUpperCase();
                            } else {
                                sortString = "#";
                            }

                            // ������ʽ���ж�����ĸ�Ƿ���Ӣ����ĸ
                            if (sortString.matches("[A-Z]")) {
                                changelist.get(i).setShouzimu(sortString.toUpperCase());
                            } else {
                                changelist.get(i).setShouzimu("#");
                            }
                        }
                        // ���a-z��������Դ���
//						Arrays.sort(datalist, pinyinComparator);
                        Collections.sort(datalist, pinyinComparator);
                        adapter.notifyDataSetChanged();

//						JSONArray jsonArray = object.getJSONArray("data");
//						for (int i = 0; i < jsonArray.length(); i++) {
//							int type = 0;
//							JSONObject object2 = jsonArray.getJSONObject(i);
//							String head = object2.getString("head");
//							String userid = object2.getString("userid");
//							String name = object2.getString("name");
//							String shouzimu = "";
//
//							// ����ת����ƴ��
//							String pinyin = characterParser.getSelling(name);
//							String sortString = "";
//							if(null != pinyin && !pinyin.equals("")){
//								sortString = pinyin.substring(0, 1).toUpperCase();
//							}else{
//								sortString = "#";
//							}

                        // ������ʽ���ж�����ĸ�Ƿ���Ӣ����ĸ
//							if(sortString.matches("[A-Z]")) {
//								shouzimu = sortString.toUpperCase();
//							} else {
//								shouzimu = "#";
//							}

//							Data_myfriendb list = new Data_myfriendb(head, userid, name,type,shouzimu);
//							datalist.add(list);
//						}
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

//				if(datalist.size() >= 0){
//					// ���a-z��������Դ���
//					Collections.sort(datalist, pinyinComparator);
////					Collections.sort(datalist, pinyinComparator);
//					adapter.notifyDataSetChanged();
//				}
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("上传", "手机号失败" + responseString);
            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.e("MainActivity","requestCode"+requestCode);

    }

    class Myadapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return datalist.size();
        }

        @Override
        public Object getItem(int i) {
            // TODO Auto-generated method stub
            return i;
        }

        @Override
        public long getItemId(int i) {
            // TODO Auto-generated method stub
            return i;
        }

        public class Holder {
            ImageView iconcheck;
            ImageView usericon;
            TextView textname, tvLetter, textpr, textci;
            View address;
        }

        /**
         * ���ListView�ĵ�ǰλ�û�ȡ���������ĸ��Char asciiֵ
         */
        public int getSectionForPosition(int position) {
            if (datalist.size() == 0) {
                return -1;
            }
            return datalist.get(position).shouzimu.charAt(0);
        }

        /**
         * ��ݷ��������ĸ��Char asciiֵ��ȡ���һ�γ��ָ�����ĸ��λ��
         */
        public int getPositionForSection(int section) {
            for (int i = 0; i < getCount(); i++) {
                String sortStr = datalist.get(i).shouzimu;
                char firstChar = sortStr.toUpperCase().charAt(0);
                if (firstChar == section) {
                    return i;
                }
            }
            return -1;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewgroup) {
            Holder holder = null;
            if (convertView == null) {
                holder = new Holder();
                convertView = minflater.inflate(R.layout.friendb_item_layout, null);
                holder.usericon = (ImageView) convertView.findViewById(R.id.item_friendb_icon);
                holder.iconcheck = (ImageView) convertView.findViewById(R.id.item_friendb_iconcheck);
                holder.textname = (TextView) convertView.findViewById(R.id.item_friendb_text);
                holder.textpr = (TextView) convertView.findViewById(R.id.item_friendb_textp);
                holder.textci = (TextView) convertView.findViewById(R.id.item_friendb_textc);
                holder.tvLetter = (TextView) convertView.findViewById(R.id.catalog);
                holder.address = convertView.findViewById(R.id.item_friendb_address);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            holder.iconcheck.setVisibility(View.GONE);
            holder.address.setVisibility(View.VISIBLE);
            Datas_freinds myfriend = datalist.get(position);
            // ���position��ȡ���������ĸ��Char asciiֵ
            int section = getSectionForPosition(position);

            // ���ǰλ�õ��ڸ÷�������ĸ��Char��λ�� ������Ϊ�ǵ�һ�γ���
            if (position == getPositionForSection(section)) {
                holder.tvLetter.setVisibility(View.VISIBLE);
                holder.tvLetter.setText(myfriend.getShouzimu());
            } else {
                holder.tvLetter.setVisibility(View.GONE);
            }
            holder.textname.setText(myfriend.getName());
            holder.textpr.setText("");
            holder.textci.setText("");
//            imageLoader.DisplayImage("http://" + myfriend.getHead(), holder.usericon, false, true, false, 0);
            return convertView;
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fmnearby_relative_friend:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(getActivity(), FriendsActivity.class);
                    startActivity(intent);
//                    Toast.makeText(getContext(),"暂未开放，敬请期待。",Toast.LENGTH_SHORT).show();


                }
//                getToken();
                break;

            case R.id.fmnearby_imge_add:
                if (null == loaded) {
                    Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(getActivity(), AddfriendActivity.class);
                    startActivity(intent);
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterview, View view, int i, long l) {


//        String userid = datalist.get(i).userid;
//        Intent intent = new Intent(getActivity(), FriendinfoActivity.class);
//        intent.putExtra("userid", userid);
//        startActivity(intent);
        accid=datalist.get(i).getAccid();
        getToken(accid);
//        getYunxunList();


    }
    private void onLoginDone() {
        loginRequest = null;
        DialogMaker.dismissProgressDialog();
    }
    // 获取云信登录token
    public void getToken(final String accid) {
        loaded=application.getDatas_load();
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",loaded.getId());
        Log.e("获取云信登录token params",params.toString());
        Log.e("获取云信登录token url", Constant.YXTAKEN_URL);
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.YXTAKEN_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                //判断状态码
                if(i == 200){
                    //获取结果
                    try {
                        String result = new String(bytes, "utf-8");
                        //                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("获取云信登录token Result", result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String infro=jsonObject.getString("info");
                            if (jsonObject.getString("flag").equals("success")) {
                                String token=jsonObject.getJSONObject("data").getJSONObject("data").getString("token");
                                final String account=jsonObject.getJSONObject("data").getJSONObject("data").getString("accid");
                                loginRequest=NimUIKit.login(new LoginInfo(account, token), new RequestCallback<LoginInfo>() {
                                    @Override
                                    public void onSuccess(LoginInfo loginInfo) {

                                        Log.e("获取云信登录token","登录成功");
//                                        if (EasyPermissions.hasPermissions (getContext(), BASIC_PERMISSIONS)) {
//                                            // Already have permission, do the thing
//                                            // ...
//                                            NimUIKit.startP2PSession(getContext(), accid);
//                                        } else {
//                                            // Do not have permissions, request them now
//                                            EasyPermissions.requestPermissions (getActivity(), "需要读取权限",
//                                                    READ_AND_WRITE_STORE_MY, BASIC_PERMISSIONS);
//                                        }
                                        methodRequiresTwoPermission ();

                                    }

                                    @Override
                                    public void onFailed(int i) {
                                        Log.e("获取云信登录token","登录失败");

                                    }

                                    @Override
                                    public void onException(Throwable throwable) {

                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.e("onFailure",new String(bytes).toString());
            }
        });
    }
    // 获取云信会有列表
    public void getYunxunList() {
        loaded=application.getDatas_load();
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",loaded.getId());
        Log.e("获取云信会有列表 params",params.toString());
        Log.e("获取云信会有列表 url", Constant.YXFRIENDLIST_URL);
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.YXFRIENDLIST_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                //判断状态码
                if(i == 200){
                    //获取结果
                    try {
                        String result = new String(bytes, "utf-8");
                        //                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("获取云信会有列表 Result", result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getString("flag").equals("success")){
                            JSONArray  jsonArray=jsonObject.getJSONObject("data").getJSONArray("data");
                            Gson gson=new Gson();
                            datalist.clear();
                            ArrayList<Datas_freinds> changelist=new ArrayList<>();
                            for (int i1 = 0; i1 < jsonArray.length(); i1++) {
                                Datas_freinds datas_freinds=gson.fromJson(jsonArray.getString(i1),Datas_freinds.class);
                                if (!loaded.getId().equals(datas_freinds.getUser_id())){
                                    changelist.add(datas_freinds);
                                }
                            }
                            for (int j = 0; j < changelist.size(); j++) {
                                // ����ת����ƴ��
                                String sortString = "";
                                String name = changelist.get(j).getName();
                                String pinyin = "#";
                                Log.e("name", "ss" + name);
                                if (null != name) {
                                    pinyin = characterParser.getSelling(name);
                                }
                                if (null != pinyin && !pinyin.equals("")) {
                                    sortString = pinyin.substring(0, 1).toUpperCase();
                                } else {
                                    sortString = "#";
                                }

                                // ������ʽ���ж�����ĸ�Ƿ���Ӣ����ĸ
                                if (sortString.matches("[A-Z]")) {
                                    changelist.get(j).setShouzimu(sortString.toUpperCase());
                                } else {
                                    changelist.get(j).setShouzimu("#");
                                }
                            }
                            // ���a-z��������Դ���
//
                                datalist.addAll(changelist);
                        Log.e("datalist",datalist.get(0).toString()+"");
                            Collections.sort(datalist, pinyinComparator);
                            adapter.notifyDataSetChanged();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.e("onFailure",new String(bytes).toString()+"");
//                Toast.makeText(getContext(),"您没有权限",Toast.LENGTH_LONG).show();
            }
        });
    }
    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
//            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult (requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);

    }

    @AfterPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(getContext(), BASIC_PERMISSIONS)) {
            // Already have permission, do the thing
            NimUIKit.startP2PSession(getContext(), accid);
            Log.e ("MainActivity", "已经获得读写本地文件的权限云信");
            // ...
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(NearbyFragment.this, "需要读取限",
                    BASIC_PERMISSION_REQUEST_CODE, BASIC_PERMISSIONS);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void UpdateList(YxListEvent messageEvent) {
        Log.e("xListEvent","接收到了");
        datalist.clear();
        getYunxunList();
    }
}
